package com.kidback.bbloc259.network.interceptor;

import android.net.Uri;
import android.os.Build;

import com.kidback.bbloc259.network.base.INetWorkConfig;
import com.kidback.bbloc259.network.utils.SignUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by meikai on 2020/05/16.
 */
public class HttpRequestInterceptor implements Interceptor {

    private INetWorkConfig iNetWorkRequiredInfo;

    public HttpRequestInterceptor(INetWorkConfig iNetWorkRequiredInfo) {
        this.iNetWorkRequiredInfo = iNetWorkRequiredInfo;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Uri originalUri = Uri.parse(chain.request().url().toString());
        Uri.Builder uriBuilder = originalUri.buildUpon();

        String signValue = SignUtils.getSign(chain.request(), uriBuilder);
        uriBuilder.appendQueryParameter("sign", signValue);

        Uri uri = uriBuilder.build();

        Request.Builder builder = chain.request().newBuilder();
        builder.url(uri.toString());

//        String token = iNetWorkRequiredInfo.getAuthToken();
//        if (token != null && token.length() > 0) {
//            builder.header("authToken", token);
//        }
//        builder.header("stat_id", iNetWorkRequiredInfo.getStatId());
//        builder.header("brand", Build.BRAND);
//        builder.header("model", Build.MODEL);
//        builder.header("manufacturer", Build.MANUFACTURER);
//        builder.header("os", "android");
//        builder.header("appName", URLEncoder.encode(iNetWorkRequiredInfo.getAppName(), "utf-8"));
//        builder.header("appVersionName", iNetWorkRequiredInfo.getAppVersionName());
//        builder.header("appVersionCode", iNetWorkRequiredInfo.getAppVersionCode());
//        builder.header("source", "source");
//        builder.header("channel", iNetWorkRequiredInfo.getChannel());
//        builder.header("Date", Calendar.getInstance().getTime().toString());
//
//        List<String> keyList = iNetWorkRequiredInfo.getHeaderKeyList();
//        List<String> valueList = iNetWorkRequiredInfo.getHeaderValueList();
//        if (keyList != null && valueList != null) {
//            for (int i = 0; i < keyList.size(); i++) {
//                builder.header(keyList.get(i), valueList.get(i));
//            }
//        }

        Request request = builder.build();

        Response response = chain.proceed(request);

        return response;
    }


}
